import React, { useState, useEffect } from 'react';
import { Calendar, Badge, Card, Select, Spin, message } from 'antd';
import { getDepartmentList, getAssetUsage } from '../../../services/api';
import dayjs from 'dayjs';

const DepartmentUsageCalendar = () => {
  const [loading, setLoading] = useState(false);
  const [departments, setDepartments] = useState([]);
  const [usageData, setUsageData] = useState({});
  const [selectedDepartment, setSelectedDepartment] = useState('all');

  // 获取部门列表
  const fetchDepartments = async () => {
    try {
      const response = await getDepartmentList();
      if (response.code === 200 && Array.isArray(response.data)) {
        setDepartments(response.data);
      } else {
        message.error(response.message || '获取部门列表失败');
      }
    } catch (error) {
      console.error('获取部门列表失败:', error);
      message.error('获取部门列表失败');
    }
  };

  // 获取使用数据
  const fetchUsageData = async (date) => {
    setLoading(true);
    try {
      // 打印请求参数
      const params = {
        month: date.format('YYYY-MM'),
        depId: selectedDepartment
      };
      console.log('请求参数:', params);

      const response = await getAssetUsage(params);
      console.log('API响应:', response);  // 打印API响应
      
      if (response.code === 200) {
        // 将借用数据转换为日历显示格式
        const formattedData = {};
        if (Array.isArray(response.data)) {
          response.data.forEach(item => {
            // 打印原始数据
            console.log('处理记录:', item);
            
            // 确保borrowTime是有效的日期字符串
            if (!item.borrowTime) {
              console.warn('记录缺少borrowTime:', item);
              return;
            }

            // 尝试多种日期格式
            let dateStr;
            try {
              // 首先尝试解析标准格式
              let date = dayjs(item.borrowTime);
              if (!date.isValid()) {
                // 如果不是标准格式，尝试解析中文格式
                const match = item.borrowTime.match(/(\d+)月 (\d+), (\d+)/);
                if (match) {
                  const [_, month, day, year] = match;
                  date = dayjs(`${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`);
                }
              }
              
              if (!date.isValid()) {
                console.warn('无法解析日期:', item.borrowTime);
                return;
              }
              
              dateStr = date.format('YYYY-MM-DD');
              console.log('解析后的日期:', dateStr);
            } catch (error) {
              console.error('日期解析失败:', error);
              return;
            }
            
            if (!formattedData[dateStr]) {
              formattedData[dateStr] = [];
            }
            
            // 根据借用状态设置不同的标记类型
            let type = 'processing';
            if (item.borrowStatus === '已批准' || item.borrowStatus === 'approved' || item.borrowStatus === '借用中') {
              type = 'success';
            } else if (item.borrowStatus === '已拒绝' || item.borrowStatus === 'rejected') {
              type = 'error';
            } else if (item.borrowStatus === '已归还' || item.borrowStatus === 'returned') {
              type = 'default';
            }
            
            formattedData[dateStr].push({
              type,
              content: `${item.assetName} - ${item.depName} (${item.borrowStatus})`
            });
          });
        } else {
          console.warn('响应数据不是数组:', response.data);
        }
        
        console.log('格式化后的数据:', formattedData);  // 打印格式化后的数据
        setUsageData(formattedData);
      } else {
        message.error(response.message || '获取使用数据失败');
      }
    } catch (error) {
      console.error('获取使用数据失败:', error);
      message.error('获取使用数据失败');
    }
    setLoading(false);
  };

  // 初始化加载
  useEffect(() => {
    fetchDepartments();
  }, []);

  // 当选择的部门变化时重新加载数据
  useEffect(() => {
    console.log('选择的部门变化:', selectedDepartment);
    const currentDate = dayjs();
    console.log('当前日期:', currentDate.format('YYYY-MM-DD'));
    fetchUsageData(currentDate);
  }, [selectedDepartment]);

  // 日历单元格渲染
  const dateCellRender = (value) => {
    const dateStr = value.format('YYYY-MM-DD');
    const listData = usageData[dateStr] || [];

    console.log(`渲染日期 ${dateStr}, 数据:`, listData);

    if (listData.length === 0) {
      return null;
    }

    return (
      <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
        {listData.map((item, index) => (
          <li key={index} style={{ marginBottom: '2px' }}>
            <Badge status={item.type} text={item.content} />
          </li>
        ))}
      </ul>
    );
  };

  // 月份变化处理
  const onPanelChange = (date) => {
    console.log('月份变化:', date.format('YYYY-MM'));
    fetchUsageData(date);
  };

  return (
    <Card title="部门资产使用日历" style={{ margin: '24px' }}>
      <div style={{ marginBottom: '16px' }}>
        <Select
          style={{ width: 200 }}
          value={selectedDepartment}
          onChange={value => {
            console.log('选择部门:', value);
            setSelectedDepartment(value);
          }}
          placeholder="选择部门"
        >
          <Select.Option value="all">所有部门</Select.Option>
          {departments.map(dept => (
            <Select.Option key={dept.depId} value={dept.depId}>
              {dept.depName}
            </Select.Option>
          ))}
        </Select>
      </div>
      
      <Spin spinning={loading}>
        <Calendar
          dateCellRender={dateCellRender}
          onPanelChange={onPanelChange}
          mode="month"
        />
      </Spin>
    </Card>
  );
};

export default DepartmentUsageCalendar; 